package com.lagou.rpc.consumer.client;

import com.lagou.rpc.consumer.config.RpcAddr;

import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author liuc
 * @date 2021/6/8
 * @description
 **/
public class RpcClientFactory {
    private Map<String, RpcAddr> rpcAddrMap = new ConcurrentHashMap<>();

    public void put(String key, RpcAddr rpcAddr){
        rpcAddrMap.put(key,rpcAddr);
    }

    public void remove(String key){
        rpcAddrMap.remove(key);
    }

    public RpcAddr get(String key){
        return rpcAddrMap.get(key);
    }

    public RpcAddr get(){
        if(rpcAddrMap.size() == 0){
            throw new NullPointerException("no rpc address found!");
        }
        Collection<RpcAddr> values = rpcAddrMap.values();
        printServerInfo(values);
        RpcAddr res = null;
        for (RpcAddr ra : values) {
            if(ra.getLastTime() == 0){
                res = ra;
                break;
            }
            if(res == null){
                res = ra;
            }
            if(ra.getLastTime() < res.getLastTime()){
                res = ra;
            }
        }
        System.out.println("===== choose rpc server , host : " + res.getHost() + " , port : " + res.getPort() + ", last time : " + res.getLastTime());
        return res;
    }

    private void printServerInfo(Collection<RpcAddr> values){
        values.forEach(res -> System.out.println("find rpc server , host : " + res.getHost() + " , port : " + res.getPort() + ", last time : " + res.getLastTime()));
    }
}
